package com.example.demo.dao;

import com.example.demo.model.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.xml.ws.Action;
import java.time.Duration;

/**
 * 功能描述：
 *
 * @Author: Zhanghf
 * @Date: 2021/12/13 8:36
 */
@Service
public class BookRedis {
    @Autowired
    RedisTemplate<String, Book> bookRedisTemplate;
    /*
        @Autowired
    RedisTemplate<String, Book> bookRedisTemplate;
报错未能加载到ApplicationContext，原因是自定义的bookRedisTemplate不能自动创建

默认如果没有配置redisTemplate，即使用自带的RedisTemplate<Object, Object>
需要在配置类对自定义的RedisTemplate进行配置

    */
//只是 @Autowired(required = false)
//    RedisTemplate<String, Book> bookRedisTemplate;
//    会报空指针异常
//
    public  void a() {
/*        Book book = new Book(1,"a","b","c","d","e","f");
        bookRedisTemplate.expire("book", Duration.ofDays(20));

        ValueOperations<String, Book> stringBookValueOperations = bookRedisTemplate.opsForValue();
//         中间出现只有expire(K key, long timeout, TimeUnit unit)
//         没有expire(K key, Duration timeout)
//        redis版本跟1.0不一致
//        设置Redis一致后还是没有生效
//        redis相关依赖对springboot版本有要求
//        修改了当前项目的boot版本才生效
         stringBookValueOperations.set(book.getId().toString(),book);
        HashOperations<String, Object, Object> stringObjectObjectHashOperations = bookRedisTemplate.opsForHash();
        stringObjectObjectHashOperations.put("book",book.getId(),book);*/
     }

    public  void insertToRedis(Book book) {
  /*      HashOperations<String, Object, Object> stringObjectObjectHashOperations = bookRedisTemplate.opsForHash();
        stringObjectObjectHashOperations.put("book",book.getId(),book);*/
//        Integer bookId = book.getId();
//        stringObjectObjectHashOperations.put("book"+bookId,"id",bookId);
//        stringObjectObjectHashOperations.put("book"+bookId,"name",book.getName());
//        stringObjectObjectHashOperations.put("book"+bookId,"type",book.getType());
//        stringObjectObjectHashOperations.put("book"+bookId,"author",book.getAuthor());
//        stringObjectObjectHashOperations.put("book"+bookId,"introduction",book.getIntroduction());
//        stringObjectObjectHashOperations.put("book"+bookId,"source",book.getSource());
//        stringObjectObjectHashOperations.put("book"+bookId,"url",book.getUrl());

    }
    public  void selectFromRedisByid(Integer bookid) {
        HashOperations<String, Object, Object> stringObjectObjectHashOperations = bookRedisTemplate.opsForHash();
         stringObjectObjectHashOperations.get("book",bookid);
    }

    public  void deleteByid(Integer bookid) {
        HashOperations<String, Object, Object> stringObjectObjectHashOperations = bookRedisTemplate.opsForHash();
        bookRedisTemplate.delete("book"+bookid);
    }

}
